<template>
  <div class="login-container">
    <el-form
      :model="loginUser"
      :rules="rules"
      ref="loginForm"
      class="login-form"
    >
      <el-form-item prop="email">
        <el-input
          prefix-icon="el-icon-user"
          placeholder="请输入邮箱"
          v-model="loginUser.email"
        ></el-input>
      </el-form-item>
      <el-form-item prop="password">
        <el-input
          prefix-icon="el-icon-view"
          placeholder="请输入密码"
          type="password"
          v-model="loginUser.password"
        ></el-input>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          @click="submitForm('loginForm')"
          class="login-btn"
          >登录</el-button
        >
      </el-form-item>
      <span
        >还没有账号？点击<router-link to="/register">注册</router-link></span
      >
    </el-form>
  </div>
</template>
<script>
import jwt_decode from 'jwt-decode';
export default {
  name: "login",

  data() {
    return {
      loginUser: {
        email: "",
        password: "",
      },
      rules: {
        email: [
          { required: true, message: "请输入邮箱地址", trigger: "blur" },
          {
            type: "email",
            message: "请输入正确的邮箱地址",
            trigger: ["blur", "change"],
          },
        ],
        password: [
          {
            required: true,
            trigger: "blur",
            message: "密码不能为空！",
          },
          {
            min: 2,
            max: 20,
            message: "长度在2到20个字符内！",
            trigger: "blur",
          },
        ],
      },
    };
  },
  methods: {
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$axios.post("/api/user/login", this.loginUser).then((res) => {
            // console.log(res)
            //拿到token
            const { token } = res.data;
            //存储到localstorage
            localStorage.setItem("FundToken", token);
            //解析token
            const decode = jwt_decode(token);
            // console.log(decode)
            //token存储到vuex中
            this.$store.dispatch("setAutnenticated",this.isEmpty(decode));
            this.$store.dispatch("setUser",decode);
            this.$router.push("/");
          });
        }
      });
    },
    //传递值空，返回真，值不为空，返回假
    isEmpty(value) {
      return (
        value === undefined ||
        value === null ||
        (typeof value === "object" && Object.keys(value).length === 0) ||
        (typeof value === "string" && value.trim().length === 0)
      );
    }
  },
};
</script>
<style lang="less" scoped>
.login-container {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  background: url("../assets/login-bg.jpg") no-repeat;
  background-size: 100% 100%;
}
.login-form {
  background: white;
  width: 300px;
  padding: 50px;
  margin: 50px;
}
.login-btn {
  width: 100%;
}
</style>

